﻿using AJWPFAdmin.Core.Components.AJFilePicker.ViewModels;
using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Components.ViewModels;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Core.Validation;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Services.EF;
using Prism.Commands;
using Prism.Events;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;

namespace EntranceGuardManager.Modules.Main.ViewModels
{
    public class IllegalVehicleUploadCheckFormViewModel : AnnotationValidationViewModel, IDialogAware
    {
        private string _dialogTitle;
        public string DialogTitle
        {
            get { return _dialogTitle; }
            set { SetProperty(ref _dialogTitle, value); }
        }

        private bool _loading;
        public bool Loading
        {
            get { return _loading; }
            set { SetProperty(ref _loading, value); }
        }

        private int _checkResult;
        /// <summary>
        /// 核实结果 0—超标；1—不超标
        /// </summary>
        public int CheckResult
        {
            get => _checkResult;
            set => SetProperty(ref _checkResult, value);
        }

        private string _fleetName;
        /// <summary>
        /// 车队名,自有、个人或运输
        /// </summary>
        [Display(Name = "车队名")]
        [Required(ErrorMessage = "{0}必填")]
        [MaxLength(100,ErrorMessage = "{0}超长:{1}")]
        public string FleetName
        {
            get => _fleetName;
            set => SetProperty(ref _fleetName, value);
        }

        private IllegalVehicleRecord _record;
        public IllegalVehicleRecord Record
        {
            get => _record;
            set => SetProperty(ref _record, value);
        }

        private AJGlobalExceptionResolvedEvent _globalExceptionEvt;
        private AppointAPISvc _appointSvc;
        private DbService db;

        public IllegalVehicleUploadCheckFormViewModel(DbService dbIns, 
            AppointAPISvc appointAPISvc, 
            IEventAggregator eventAggregator)
        {
            _appointSvc = appointAPISvc;
            _globalExceptionEvt = eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>();
            _globalExceptionEvt.Subscribe(() =>
            {
                Loading = false;
            });
            db = dbIns;
            
            DialogTitle = string.Empty;
        }

        private DelegateCommand _saveCmd;
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSaveCmdAsync, CanExecuteSaveCmd));

        async void ExecuteSaveCmdAsync()
        {
            if (!ValidateModel())
            {
                SaveCmd.RaiseCanExecuteChanged();

                AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = "提示",
                    Message = $"表单校验失败,请检查所填数据",
                    Detail = string.Join(";", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString()))
                });
                return;
            }

            Loading = true;

            var result = await _appointSvc.API.CheckIllegalVehiclesAsync(new CheckIllegalVehicleParams
            {
                PlateNo = _record.CarNo,
                PlateColor = _record.Color,
                VIN = _record.VIN,
                CheckResult = CheckResult,
                FleetName = FleetName
            });

            if (!result.Success)
            {
                AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = $"{_appointSvc.API.KeyDescription} 超标信息核实结果上送接口提示",
                    Message = result.Message,
                    Detail = result.Data is Exception ex ? ex.StackTrace : string.Empty
                });
                Loading = false;
                return;
            }

            _record.CheckResult = CheckResult;
            _record.FleetName = FleetName;
            _record.UpdateDate = DateTime.Now;
            db.Entry(_record).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            await db.SaveChangesAsync();

            Loading = false;

            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));

        }

        bool CanExecuteSaveCmd()
        {
            return !HasErrors;
        }

        public string Title => string.Empty;

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            parameters.TryGetValue<IllegalVehicleRecord>("data", out var rcd);

            Record = rcd;

            DialogTitle = $"{_record.CarNo} 违规核查上送";
        }
    }
}
